package com.taiyi.renaissancemall.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.provider.Settings;
import android.util.Log;

import androidx.multidex.MultiDexApplication;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.SPCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.taiyi.renaissancemall.Utils.Utils;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

public class MyApp extends MultiDexApplication {
    private static MyApp instance;
    public static String APP_ID = "wx54586503773d580c";

    //oss 2
    private static OSSClient mOSSClient;
    public static String accessKeyId = "LTAI4FwuxFW38WHwpFtmnsKV";
    public static String accessKeySecret = "Y2oaSJywHbB7jIZcBxbggRHWh0cLYI";
    public static String endpoint = "http://oss-cn-beijing.aliyuncs.com/";

    public static int getOpenId = 1;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        Utils.init(this);
        initOkGo();
        initBugly();
        regToWx();
        //oss 3
        initOss();

    }

    // IWXAPI 是第三方app和微信通信的openApi接口
    public static IWXAPI api;

    private void regToWx() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, APP_ID, true);

        // 将应用的appId注册到微信
        api.registerApp(APP_ID);

        //建议动态监听微信启动广播进行注册到微信
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // 将该app注册到微信
                api.registerApp(APP_ID);
            }
        }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));

    }

    public static String getAppId() {
        return APP_ID;
    }

    public static IWXAPI getWxApi() {
        return api;
    }

    private void initBugly() {
        CrashReport.initCrashReport(getApplicationContext(), "7f86329bfd", false);
    }

    public static String getAndroidID() {
        String id = Settings.Secure.getString(
                getInstance().getContentResolver(),
                Settings.Secure.ANDROID_ID
        );
        return id == null ? "" : id;
    }


    public static String getDeviceUUid() {
        String androidId = getAndroidID();
        UUID deviceUuid = new UUID(androidId.hashCode(), ((long) androidId.hashCode() << 32));
        Log.i("deviceId", "---androidId---" + androidId + "---uuid---" + deviceUuid.toString());
        return deviceUuid.toString();
    }


    public void initOkGo() {
        HttpHeaders headers = new HttpHeaders();
//        if (new SPCookieStore(this).getAllCookie().size() != 0) {
//            headers.put("Set-Cookie", String.valueOf(mSPCookieStore.getCookie(HttpUrl.parse(BaseUrl.HTTP_Get_code_auth))));
//        }
        headers.put("version", "3.0");
//        if (Utils.getSpUtils().getString("loginmode", "").equals("phone")) {
//            headers.put("uid", MyApplication.getDaoInstant().getUserBeanDao().queryBuilder().where(UserBeanDao.Properties.Wallet_phone.eq(Utils.getSpUtils().getString("firstUser"))).build().unique().getWallet_uid());
//        } else {
//            headers.put("uid", "6f1a8e0eb24afb7ddc829f96f9f74e9d");
//        }


        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //log相关
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkHttp");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别，决定了log在控制台显示的颜色
        builder.addInterceptor(loggingInterceptor);                                 //添加OkGo默认debug日志
        //超时时间设置
        builder.readTimeout(30000, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(30000, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(30000, TimeUnit.MILLISECONDS);   //全局的连接超时时间
        builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));            //使用sp保持cookie，如果cookie不过期，则一直有效


//        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(getAssets().open("server.cer"));
//        builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
////        //配置https的域名匹配规则，使用不当会导致https握手失败
//        builder.hostnameVerifier(HttpsUtils.UnSafeHostnameVerifier);

        // 其他统一的配置
        OkGo.getInstance().init(this)                           //必须调用初始化
                .setOkHttpClient(builder.build())               //必须设置OkHttpClient
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(0)          //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
                .addCommonHeaders(headers);              //全局公共头
//                .addCommonParams(httpParams);                       //全局公共参数

    }

    private void initOss() {
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(300 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(300 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(8); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次

        // oss为全局变量，OSS_ENDPOINT是一个OSS区域地址 oss-cn-beijing.aliyuncs.com
        mOSSClient = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
    }

    public static OSSClient getOssClient() {
        return mOSSClient;
    }

    public static MyApp getInstance() {
        return instance;
    }

}
